<template>
  <table class="search-box">
    <tr class="vat">
      <td class="search">
        <el-input placeholder="订单编号/用户名称/支付方式/订单状态" clearable class="keyword ml10" v-model="searchKeyword"
          @input="inputSearch">
          <template #prepend>关键字</template>
        </el-input>
        <!-- <el-button type="primary" class="ml10" @click="orderSearch">搜索</el-button>
          <el-button @click="clearSearch">清空</el-button> -->
        <el-button type="primary" @click="reload"> 刷新 </el-button>
      </td>
      <!-- <td class="tar">
        </td> -->
    </tr>
  </table>
  <div class="demo-pagination-block">
    <div class="demonstration">
      <el-table v-loading="loading" :data="paginatedItems" style="width: 100%">
        <el-table-column label="订单编号" prop="order_id" />
        <el-table-column label="提交时间" prop="order_time" />
        <el-table-column label="用户名称" prop="name" />
        <el-table-column label="订单金额">
          <template #default="scope">
            {{ scope.row.order_money }}元
          </template>
        </el-table-column>
        <el-table-column label="支付方式" prop="order_pay" />
        <el-table-column label="订单状态" prop="order_status">
          <template #default="scope">
            <el-select v-model="scope.row.order_status" @change="updateOrderStatus(scope.row)">
              <el-option label="待支付" value="待支付"></el-option>
              <el-option label="待发货" value="待发货"></el-option>
              <el-option label="已发货" value="已发货"></el-option>
              <el-option label="已完成" value="已完成"></el-option>
              <el-option label="已取消" value="已取消"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="order_note" />
        <el-table-column align="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="showitemsDialog(scope.row)">详情</el-button>
            <el-button size="small" type="danger" @click="showDeleteDialog(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog v-model="detailsDialogVisible" title="订单详情" width="60%">
      <el-table :data="selectedOrderItems" style="width: 100%">
        <el-table-column prop="image" label="图片">
          <template #default="scope">
            <img :src="scope.row.image" style="width: 80px; height: 80px;">
          </template>
        </el-table-column>
        <el-table-column prop="title" label="书名" />
        <el-table-column prop="book_num" label="数量" />
        <el-table-column prop="price" label="单价">
          <template #default="scope">
            {{ scope.row.price }}元
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="detailsDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[15, 30, 60, 120, 240]"
      :small="small" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
      :total="totalItems" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  </div>
  <el-dialog v-model="deleteDialogVisible" title="确认删除" width="30%">
    <p>确认要删除这条订单吗？</p>
    <template #footer>
      <el-button @click="deleteDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmDeleteOrder">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";
import _ from "lodash";

const currentPage = ref(1);
const pageSize = ref(15);
const small = ref(true);
const background = ref(true);
const disabled = ref(false);
const detailsDialogVisible = ref(false);
const selectedOrderItems = ref([]);

const handleSizeChange = (val) => {
  console.log(`${val} items per page`);
};

const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`);
};

const orders = ref([]);
const totalItems = ref(0);

const paginatedItems = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return orders.value.slice(start, end);
});

const loading = ref(false);

const fetchOrders = async () => {
  loading.value = true;
  try {
    const response = await axios.get("http://localhost:3000/api/orders/orderinfo");
    await new Promise(resolve => setTimeout(resolve, 400));
    orders.value = response.data;
    totalItems.value = response.data.length;
  } catch (error) {
    if (error.response && error.response.data && error.response.data.message) {
      ElMessage.error(error.response.data.message);
    }
  } finally {
    loading.value = false;
  }
};

async function updateOrderStatus(order) {
  try {
    const response = await axios.put(`http://localhost:3000/api/orders/updateOrderStatus/${order.order_id}`, {
      status: order.order_status
    });
    ElMessage.success(response.data.message);
  } catch (error) {
    ElMessage.error(error.response.data.message);
  }
}

onMounted(() => {
  fetchOrders();
});

const deleteDialogVisible = ref(false);
const selectedOrder = ref(null);

function showDeleteDialog(order) {
  selectedOrder.value = order;
  deleteDialogVisible.value = true;
}

async function confirmDeleteOrder() {
  try {
    const response = await axios.delete(
      `http://localhost:3000/api/orders/orderdelete/${selectedOrder.value.order_id}`
    );
    ElMessage.success(response.data.message);
    deleteDialogVisible.value = false;
    fetchOrders();
  } catch (error) {
    ElMessage.error(error.response.data.message);
  }
}

const searchKeyword = ref("");
const inputSearch = _.debounce(() => {
  if (searchKeyword.value.trim() !== "") {
    orderSearch();
  } else {
    fetchOrders();
  }
}, 300);

const orderSearch = async () => {
  try {
    const response = await axios.get("http://localhost:3000/api/orders/ordersearch", {
      params: { keyword: searchKeyword.value },
    });
    orders.value = response.data;
    totalItems.value = response.data.length;
  } catch (error) {
    ElMessage.error("搜索失败");
  }
};

function clearSearch() {
  searchKeyword.value = "";
  fetchOrders();
}

function reload() {
  location.reload();
}

async function showitemsDialog(order) {
  try {
    const response = await axios.get("http://localhost:3000/api/orders/getorderdetail", {
      params: { orderId: order.order_id }
    });
    selectedOrderItems.value = response.data;
    detailsDialogVisible.value = true;
  } catch (error) {
    ElMessage.error("获取订单详情失败");
  }
}

</script>

<style scoped>
.search-box {
  margin: 12px 4px 30px 0px;
  width: 40%;
}

.search {
  display: flex;
  padding: 0;
}

.search .el-button {
  margin-right: 10px;
}

/* .search .ml10 {
    margin-left: 10px;
  } */

.search .el-input {
  margin-right: 10px;
}

.search .el-button:last-child {
  margin-right: 0;
}

.tar {
  margin: 0px;
}

.tar .el-button {
  margin-left: 10px;
}

.demo-pagination-block {
  height: 90%;
}

.demonstration {
  height: 90%;
}

.el-table {
  height: 97.5%;
}

.el-table-column {
  height: 10rem;
}

.el-pagination {
  position: absolute;
  z-index: 100;
  bottom: 2rem;
  left: 47rem;
  background-color: whitesmoke;
  padding: 10px;
  border-radius: 25px;
}
</style>